const fs = require('fs');
const query = require('../utils/query')
var request = require('request');
var rp = require('request-promise');
const join = require('path').join;

// select * from bussiness_product where product_id in ('009', '014', '025', '028', '033', '031', '021', '020', '054', '050', '019', '022', '032')

let iconSql = fs.createWriteStream(`./sql/icon.sql`);
let notProcessProductId = [];
const host = 'http://10.112.73.28:8803';
const uploadUrl = host + '/basic/upload';

(async () => {
    let updateSql = "";
    let fileNames = findSync('./icons');
    let items = fileNames.map(item => {
        return {
            product_id: item.split(".png")[0],
            name: item
        }
    })

    for (let i = 0, l = items.length; i < l; i++) {
        let item = items[i]
        var options = {
            method: 'POST',
            uri: uploadUrl,
            formData: {
                file: {
                    // value: request(icon.main_url),
                    value: fs.createReadStream(`icons/${item.name}`),
                    options: {
                        filename: `${item.product_id}.png`,
                        contentType: 'image/png'
                    }
                }
            }
        };
        let body = await rp(options)
        let data = JSON.parse(body)
        if (data.code === "0") {
            let fileId = data.data.fileId;
            updateSql += `update device_types2 set file_id = "${fileId}" where product_id = "${item.product_id}";` + '\n'
        } else {
            console.log("文件上传失败", item)
        }
    }
    iconSql.write(updateSql);
    console.log("updateSql", updateSql)
    console.log("没有找到icon, productId", notProcessProductId)
})();


function findSync(startPath) {
    let result = [];

    function finder(path) {
        let files = fs.readdirSync(path);
        files.forEach((val, index) => {
            let fPath = join(path, val);
            let stats = fs.statSync(fPath);
            if (stats.isDirectory()) {
                result.push(fPath);
                // 递归读取文件夹下文件
                // finder(fPath)
            }
            ;
            // 读取文件名
            if (stats.isFile()) {
                result.push(val);
            }
        });

    }

    finder(startPath);
    console.log(result)
    return result;
}









